<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="5">
          <el-link :underline="false" class="connectionTitle" @click="beforeOpenDialog(false)">
            {{ saveConnectionName }}<i class="el-icon-edit el-icon--right"></i>
          </el-link>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <h5 class="connectionDescription">MongoDB 连接字符串</h5>
        </el-col>
      </el-row>

      <el-row>
        <el-input
            type="textarea"
            :disabled="!editConnectionStringSwitch"
            :autosize="{ minRows: 4, maxRows: 6}"
            v-model="URI">
        </el-input>
      </el-row>

      <el-collapse style="border: none;">
        <el-collapse-item>
          <template slot="title">
            <span style="font-size: 15px;font-weight: bolder;">连接选项</span>
          </template>
          <el-menu :default-active="optionsActive" mode="horizontal" @select="selectMenu">
            <el-menu-item index="first">基本的</el-menu-item>
            <el-menu-item index="second">认证方式</el-menu-item>
          </el-menu>
          <template v-if="optionsActive === 'first'">
            <el-row>
              <h3>协议</h3>
            </el-row>
            <el-row>
              <el-radio-group v-model="connectForm.protocol">
                <el-radio-button label="mongodb"></el-radio-button>
              </el-radio-group>
            </el-row>
            <el-row>
              <h4>Host</h4>
              <el-input class="host_input" v-model="host"></el-input>
            </el-row>
          </template>
          <template v-else>
            <h3>认证方式</h3>
            <el-row>
              <el-switch v-model="authenticationValue" active-text="用户名密码认证" inactive-text="无"></el-switch>
            </el-row>
            <template v-if="authenticationValue">
              <el-form :model="connectForm" ref="connectForm" :rules="rules" label-position="top" size="small">
                <el-form-item label-width="50px" prop="username">
                  <template slot="label">
                    <span class="authLabelSpan" style="font-size: 1.1em;font-weight: bolder;">用户名</span>
                  </template>
                  <el-input v-model="connectForm.username"></el-input>
                </el-form-item>
                <el-form-item label-width="50px" prop="password">
                  <template slot="label">
                    <span class="authLabelSpan">密码</span>
                  </template>
                  <el-input v-model="connectForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label-width="50px">
                  <template slot="label">
                    <span class="authLabelSpan">权限数据库</span>
                  </template>
                  <el-input v-model="connectForm.authDatabase" placeholder="可选的，默认 admin"></el-input>
                </el-form-item>
                <el-form-item label-width="50px">
                  <template slot="label">
                    <span class="authLabelSpan">认证机制</span>
                  </template>
                  <el-radio-group v-model="connectForm.authMechanism">
                    <el-radio-button label="DEFAULT"></el-radio-button>
                    <el-radio-button label="SCRAM-SHA-1"></el-radio-button>
                    <el-radio-button label="SCRAM-SHA-256"></el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </template>
          </template>
        </el-collapse-item>
      </el-collapse>

      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="4">
          <el-button plain @click="beforeOpenDialog(false)">保存</el-button>
        </el-col>
        <el-col :span="4" :offset="12">
          <el-button type="primary" plain @click="beforeOpenDialog(true)">保存并连接
          </el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="success" plain @click="connectionMongo">连接</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!--  编辑连接名对话框  -->
    <el-dialog :visible.sync="editConnectionDialogShow" width="30%" :close-on-click-modal="false"
               @closed="closeEditConnectionDialog" @opened="openEditConnectionDialog">
      <div slot="title" class="editConnectionDialogTitle">
        保存连接
      </div>
      <el-form :model="saveConnectionForm" label-position="top" size="small">
        <el-form-item label="连接名" label-width="50px">
          <el-input v-model="saveConnectionForm.name" :autofocus="true" ref="nameInput"
                    :placeholder="saveConnectionName"></el-input>
        </el-form-item>
        <el-form-item label="分组名" label-width="50px">
          <el-select v-model="saveConnectionForm.groups" placeholder="请选择" clearable multiple filterable default-first-option>
            <el-option v-for="item in saveConnectionGroups" :key="item.id" :label="item.groupName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editConnectionDialogShow = false">关闭</el-button>
        <el-button type="primary" @click="saveConnection" :disabled="saveIsDisabled">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getAllGroup} from "@/api/group";
import {addConnection} from "@/api/saveConnect";

export default {
  name: "Connection",
  data() {
    return {
      saveConnectionName: "新建连接",
      saveConnectionForm: {
        name: '',
        groups: []
      },
      saveConnectionGroups: [],
      editConnectionDialogShow: false,
      isConnect: false,
      saveIsDisabled: true,
      URI: 'mongodb://localhost:27017/',
      editConnectionStringSwitch: false,
      optionsActive: "first",
      host: "localhost:27017",
      authenticationValue: false,
      mechanismValue: null,
      connectForm: {
        // 协议
        protocol: "mongodb",
        // IP地址
        ip: "localhost",
        // 端口号
        port: "27017",
        // 认证方式
        auth: false,
        // 用户名
        username: null,
        // 密码
        password: null,
        // 权限数据库，默认admin
        authDatabase: null,
        // 权限验证机制，默认DEFAULT时Java驱动不用加上
        authMechanism: null,
      },
      rules: {
        username: [
          {required: true, message: '请输入有效的用户名！', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入有效的密码！', trigger: 'blur'},
        ],
      }
    }
  },
  watch: {
    connectForm: {
      handler(newVal) {
        this.URI = newVal.protocol + "://"
        let flag = false
        if (newVal.username !== '' && newVal.username !== null && newVal.username !== undefined) {
          this.URI += newVal.username
          flag = true
        }
        if (newVal.password !== '' && newVal.password !== null && newVal.password !== undefined) {
          this.URI += ":******"
          flag = true
        }
        if (flag) {
          this.URI += "@"
        }
        this.URI += newVal.ip + ":" + newVal.port + "/"
        if (newVal.authMechanism !== '' && newVal.authMechanism !== null && newVal.authMechanism !== undefined) {
          this.URI += "?authMechanism=" + newVal.authMechanism
        }
        if (newVal.authDatabase !== '' && newVal.authDatabase !== null && newVal.authDatabase !== undefined) {
          this.URI += "&authSource=" + newVal.authDatabase
        }
      },
      deep: true
    },
    host: {
      handler(newVal) {
        const split = newVal.split(":");
        this.connectForm.ip = split[0]
        this.connectForm.port = split[1]
      }
    },
    saveConnectionForm: {
      handler(newValue) {
        this.saveIsDisabled = !(newValue.name != null && newValue.name !== '' && newValue.groups.length > 0);
      },
      deep: true
    },
    authenticationValue: {
      handler(newValue) {
        if (newValue) {
          this.connectForm.authMechanism = "DEFAULT"
          this.connectForm.auth = true
        } else {
          this.connectForm.auth = false
          this.connectForm.authMechanism = null
          this.connectForm.authDatabase = null
          this.connectForm.username = null
          this.connectForm.password = null
        }
      }
    },
  },
  mounted() {
    if (this.$store.getters.getConnectionId !== null && this.$store.getters.getConnectionId !== '') {
      this.$store.dispatch("DisConnect", this.$store.getters.getConnectionId)
    }
  },
  methods: {
    selectMenu(key) {
      this.optionsActive = key
    },
    saveConnection() {
      addConnection(this.connectForm, this.saveConnectionForm).then(() => {
            this.saveConnectionName = this.saveConnectionForm.name
            this.$message.success("保存连接成功！")
            this.editConnectionDialogShow = false;
            if (this.isConnect) {
              this.connectionMongo()
            }
          }
      ).catch(() => {
        this.$message.error("保存连接失败！")
      })
    },
    beforeOpenDialog(isConnect) {
      if (this.$store.getters.getToken === null) {
        this.$message({
          type: 'error',
          message: '请登录后再进行操作！'
        })
      } else {
        this.editConnectionDialogShow = true
        this.isConnect = isConnect
      }
    },
    openEditConnectionDialog() {
      this.$refs.nameInput.focus();
      getAllGroup().then(res => {
        this.saveConnectionGroups = res.data
      })
    },
    closeEditConnectionDialog() {
      this.isConnect = false
      this.saveConnectionForm = {
        name: '',
        groups: []
      }
    },
    connectionMongo() {
      const loading = this.$loading({
        lock: true,
        text: '连接中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        let data = JSON.parse(JSON.stringify(this.connectForm))
        if (this.authenticationValue) {
          if (this.connectForm.authDatabase === '' || this.connectForm.authDatabase === undefined || this.connectForm.authDatabase === null) {
            data.authDatabase = 'admin'
          }
          this.$refs.connectForm.validate((valid) => {
            if (valid) {
              this.$store.dispatch("Connect", data).then(() => {
                this.$router.push({path: "/connection"})
              })
            } else {
              this.$message.error('用户名或密码不能为空！');
              return false;
            }
          });
        } else {
          this.$store.dispatch("Connect", data).then(() => {
            this.$router.push({path: "/connection"})
          })
        }
      }, 1000);
    }
  }
}
</script>

<style scoped>
.connectionTitle {
  font-size: 1.3em;
  font-weight: bolder;
  margin-bottom: 20px;
}

.connectionDescription {
  text-align: center;
  margin: 0 0 15px;
  background-color: #f4f4f5;
  color: #909399;
}

.editConnectionDialogTitle {
  font-size: 1.3em;
  font-weight: bolder;
}

.box-card {
  width: 1000px;
}

.host_input {
  width: 400px;
  margin-bottom: 10px;
}

.authLabelSpan {
  font-size: 1.1em;
  font-weight: bolder;
}
</style>
